package com.bw.contorller;

import com.bw.entity.PeiJian;
import com.bw.entity.WeiXiu;
import com.bw.service.WeiXiuService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class WeiXiuContorller {
    @Autowired
    private WeiXiuService wxs ;

    //列表展示
    @RequestMapping("list")
    public String List(WeiXiu weiXiu, Model model, @RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "2") Integer pageSize){
        PageInfo<WeiXiu> info=wxs.list(weiXiu,pageNum,pageSize);
        model.addAttribute("w",weiXiu);
        model.addAttribute("info",info);
        return "list";
    }

    //去添加
    @RequestMapping("toadd")
    public String toAdd(Model model,WeiXiu weiXiu){
        model.addAttribute("weiXiu",weiXiu);
        return "add";
    }
    //执行添加
    @RequestMapping("add")
    public String addWeiXiu(WeiXiu weiXiu ,Model model){

        int i=wxs.addWeiXiu(weiXiu);
        if(i>0){
            return "redirect:list";
        }
        return "add";
    }
    //获取配件
    @ResponseBody
    @RequestMapping("selectPeijian")
    public List<PeiJian> selectPeijian(){
        List<PeiJian>  list= wxs.selectPeijian();
        return list;
    }

    //获取文件
    @ResponseBody
    @RequestMapping("getFile")
    public String getFile(MultipartFile file) throws IOException {
        if(file!=null && !file.isEmpty()){
            String path="d:/pic";
            String originalFilename = file.getOriginalFilename();
            System.out.println(originalFilename);
            String s = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            File file1 = new File(path, s);
            file.transferTo(file1);
            return "/pic/"+s;
        }
        return null;
    }

    //修改前查询
    @RequestMapping("selectByid")
    public String selectByid(Model model,String danhao){
        WeiXiu weiXiu=wxs.selectByid(danhao);
        model.addAttribute("weiXiu",weiXiu);
        return "update";
    }
    //执行修改
    @RequestMapping("update")
    public String updateWeiXiu(WeiXiu weiXiu){
        int i =wxs.updateWeiXiu(weiXiu);
        if(i>0){
            return "redirect:list";
        }
        return "update";
    }

    //删除
    @ResponseBody
    @RequestMapping("deleteByid")
    public Integer deleteByid(String danhao){
        int i=wxs.deleteByid(danhao);
        return i;
    }
}
